const express = require('express');
const WebSocket = require('ws');
const fs = require('fs');
const path = require('path');

class VideoServer {
    constructor(port = 41235) {
        this.port = port;
        this.clients = new Set();
        this.app = express();
        this.wss = new WebSocket.Server({ noServer: true });
        
        this.app.use(express.json());
        
        // 处理 WebRTC offer
        this.app.post('/offer', async (req, res) => {
            try {
                const offer = req.body;
                const pc = new RTCPeerConnection();
                
                pc.on('datachannel', (channel) => {
                    console.log('收到数据通道');
                    this.clients.add(channel);
                    
                    channel.on('message', (message) => {
                        try {
                            const data = JSON.parse(message);
                            if (data.type === 'REGISTER') {
                                console.log('客户端注册成功');
                            }
                        } catch (error) {
                            console.error('处理客户端消息时出错:', error);
                        }
                    });
                    
                    channel.on('close', () => {
                        this.clients.delete(channel);
                        console.log('客户端断开连接');
                    });
                });
                
                await pc.setRemoteDescription(new RTCSessionDescription(offer));
                const answer = await pc.createAnswer();
                await pc.setLocalDescription(answer);
                
                res.json(answer);
            } catch (error) {
                console.error('处理 offer 时出错:', error);
                res.status(500).json({ error: '处理 offer 失败' });
            }
        });
        
        const server = this.app.listen(port, () => {
            console.log(`视频服务器监听端口 ${port}`);
        });
        
        server.on('upgrade', (request, socket, head) => {
            this.wss.handleUpgrade(request, socket, head, (ws) => {
                this.wss.emit('connection', ws, request);
            });
        });
    }

    async broadcastVideo() {
        try {
            const videoPath = path.join(__dirname, 'source', 'fight.mp4');
            const videoBuffer = await fs.promises.readFile(videoPath);
            
            // 将视频数据分成较小的块进行传输
            const chunkSize = 1024; // 1KB 每块
            const chunks = Math.ceil(videoBuffer.length / chunkSize);
            
            for (let i = 0; i < chunks; i++) {
                const start = i * chunkSize;
                const end = Math.min(start + chunkSize, videoBuffer.length);
                const chunk = videoBuffer.slice(start, end);
                
                // 添加块信息
                const chunkInfo = {
                    index: i,
                    total: chunks,
                    data: chunk.toString('base64')
                };
                
                // 向所有注册的客户端发送数据
                for (const client of this.clients) {
                    if (client.readyState === 'open') {
                        client.send(JSON.stringify(chunkInfo));
                    }
                }
                
                // 添加小延迟以避免网络拥塞
                await new Promise(resolve => setTimeout(resolve, 10));
            }
            
            console.log('视频广播完成');
        } catch (error) {
            console.error('广播视频时出错:', error);
        }
    }
}

module.exports = VideoServer;